package cn.com.easttech.gofishing;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SubMenu;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.com.easttech.gofishing.model.Company;
import cn.com.easttech.gofishing.model.ProductCatalog;
import cn.com.easttech.gofishing.model.ProductInfo;
import cn.com.easttech.gofishing.util.Constants;
import cn.com.easttech.gofishing.util.HttpCallBackListener;
import cn.com.easttech.gofishing.util.HttpUtil;

import static cn.com.easttech.gofishing.util.Constants.UPDATE_APK_ERROR;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private final String TAG = getClass().getSimpleName();
    private NavigationView navigationView;

    private String appUrl = null;
    private String dataUrl = null;

    private List<Company> companyList = new ArrayList<>();
    private List<ProductCatalog> productCatalogList = new ArrayList<>();
    private List<ProductInfo> productInfoList = new ArrayList<>();
    private boolean isInitComplete = false;

    private void setCompany(Company company) {

        View headerLayout = navigationView.getHeaderView(0);

        TextView companyNameView = (TextView)headerLayout.findViewById(R.id.company_name_view);
        companyNameView.setText(company.getName());

    }

    private void init() {

        if (getNetworkType() <= 0) {
            Log.i(TAG,"没有网络连线");
            return;
        }

        try {
            if (!isInitComplete) {
                Thread.sleep(1000);
            }
        } catch (Exception e) {

        }

        HttpUtil.sendGetRequest("http://www.china-fishboy.com/config.json", null, new HttpCallBackListener() {
            @Override
            public void onFinish(String respose) {
                //处理请求
                Log.d(TAG, respose);

                try {
                    appUrl = new JSONObject(respose).getString(Constants.APP_URL);
                    dataUrl = new JSONObject(respose).getString(Constants.DATA_URL);
                    String appVersion = new JSONObject(respose).getString(Constants.APP_VERSION);

                    Log.i(TAG, "appUrl:" + appUrl + "， dataUrl:" + dataUrl + "， appVersion:" + appVersion);

                    if(appVersion.equals(getVersion())){
                        Log.i(TAG,"版本号相同无需升级");

                        Message msg = new Message();
                        msg.what = Constants.UPDATE_DATA;
                        handler.sendMessage(msg);
                    }else{
                        Log.i(TAG,"版本号不同 ,提示用户升级 ");

                        Message msg = new Message();
                        msg.what = Constants.UPDATE_APK;
                        handler.sendMessage(msg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                    isInitComplete = true;
                }

            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());

                isInitComplete = true;
            }
        });

    }

    private void initCompanyList(String response) {
        try {
            JSONArray jsonArray = new JSONObject(response).getJSONArray("companylist");

            String uuid = null, name = null;

            companyList.clear();

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = (JSONObject)jsonArray.get(i);

                uuid = jsonObject.getString("uuid");
                name = jsonObject.getString("name");

                Log.d(TAG, "company: " + uuid + ", " + name);

                Company company = new Company();
                company.setUuid(uuid);
                company.setName(name);

                companyList.add(company);
            }

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void initProductCatalogList(String response) {
        try {

            productCatalogList.clear();

            JSONArray jsonArray = new JSONObject(response).getJSONArray("productcataloglist");

            String uuid = null, name = null, companyUuid = null;
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = (JSONObject)jsonArray.get(i);

                uuid = jsonObject.getString("uuid");
                name = jsonObject.getString("name");
                companyUuid = jsonObject.getString("companyuuid");

                Log.d(TAG, "productCatalog: " + uuid + ", " + name);

                ProductCatalog productCatalog = new ProductCatalog();
                productCatalog.setUuid(uuid);
                productCatalog.setName(name);
                productCatalog.setCompanyUuid(companyUuid);

                JSONArray productCataloglist = jsonObject.getJSONArray("subproductcatalog");

                for(int j = 0; j < productCataloglist.length(); j++) {

                    JSONObject jsonObject1=(JSONObject)productCataloglist.get(j);

                    uuid = jsonObject1.getString("uuid");
                    name = jsonObject1.getString("name");
                    companyUuid = jsonObject1.getString("companyuuid");

                    Log.d(TAG, "subproductcatalog: " + uuid + ", " + name);

                    ProductCatalog subProductCatalog = new ProductCatalog();
                    subProductCatalog.setUuid(uuid);
                    subProductCatalog.setName(name);
                    subProductCatalog.setCompanyUuid(companyUuid);
                    subProductCatalog.setSuperCatalogId(productCatalog.getUuid());

                    productCatalog.getSubProductCatalog().add(subProductCatalog);
                }

                productCatalogList.add(productCatalog);

                for (Company company : companyList) {
                    company.getProductCatalogList().clear();
                }

                for (Company company : companyList) {
                    if (company.getUuid().equals(productCatalog.getCompanyUuid())) {
                        company.getProductCatalogList().add(productCatalog);
                    }
                }
            }

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void initProductInfoList(String response) {
        try {
            productInfoList.clear();

            JSONArray jsonArray = new JSONObject(response).getJSONArray("productinfolist");

            String uuid = null, name = null, picture = null, textDesc = null, videoDesc = null, pictureDesc = null, catalogUuid = null, companyUuid = null, newProduct = null;
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = (JSONObject)jsonArray.get(i);

                uuid = jsonObject.getString("uuid");
                name = jsonObject.getString("name");
                picture = jsonObject.getString("picture");
                textDesc = jsonObject.getString("textdesc");
                videoDesc = jsonObject.getString("videodesc");
                pictureDesc = jsonObject.getString("picturedesc");
                catalogUuid = jsonObject.getString("cataloguuid");
                companyUuid = jsonObject.getString("companyuuid");
                newProduct = jsonObject.getString("newproduct");

                Log.d(TAG, "productcatalog: " + uuid + ", " + name);

                ProductInfo productInfo = new ProductInfo();
                productInfo.setUuid(uuid);
                productInfo.setName(name);
                productInfo.setPicture(picture);
                productInfo.setTextDesc(textDesc);
                productInfo.setVideoDesc(videoDesc);
                productInfo.setPictureDesc(pictureDesc);
                productInfo.setCatalogUuid(catalogUuid);
                productInfo.setCompanyUuid(companyUuid);
                productInfo.setNewProduct(newProduct);

                productInfoList.add(productInfo);

                for (ProductCatalog productCatalog : productCatalogList) {
                    productCatalog.getProductInfoList().clear();
                }

                for (ProductCatalog productCatalog : productCatalogList) {
                    if (productCatalog.getUuid().equals(productInfo.getCatalogUuid())) {
                        productCatalog.getProductInfoList().add(productInfo);
                    }
                }
            }

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void downloadData() {

        HttpUtil.sendGetRequest(dataUrl, null, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                //处理请求
                Log.d(TAG, response);

                initCompanyList(response);

                initProductCatalogList(response);

                initProductInfoList(response);

                if (companyList.size() > 0) {
                    setCompany(companyList.get(0));
                }

                Log.d(TAG, "downloadData isInitComplete:" + isInitComplete);
                isInitComplete = true;
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }
        });

    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.UPDATE_APK:
                    //对话框通知用户升级程序
                    showUpdataDialog(appUrl);
                    break;
                case UPDATE_APK_ERROR:
                    //下载apk失败
                    Toast.makeText(getApplicationContext(), "无法顺利下载更新，请稍后重试", Toast.LENGTH_SHORT).show();
                    break;
                case Constants.UPDATE_DATA:
                    //对话框通知用户升级程序
                    downloadData();
                    break;
                case Constants.UPDATE_DATA_ERROR:
                    //下载apk失败
                    Toast.makeText(getApplicationContext(), "无法顺利下载更新，请稍后重试", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        int networkType = getNetworkType();
        boolean b1 = isNetworkConnected();
        boolean b2 = isWifiConnected();
        boolean b3 = isMobileConnected();

        Log.d(TAG, "networkType:" + networkType + ", isNetworkConnected:" + b1 + ", isWifiConnected:" + b2 + ", isMobileConnected:" + b3);
        init();

//        Company company1 = new Company();
//        company1.setName("法雨");
//
//        Company company2 = new Company();
//        company2.setName("钓鱼郎");
//
//        companyList.add(company1);
//        companyList.add(company2);
//
//        setCompany(company1);

        //navigationView.getMenu().add(1, 1, 1, "menu_1");

        SubMenu subMenu = navigationView.getMenu().addSubMenu(1,11,11,"menu_11");

        subMenu.add(11,11,11,"menu_11_1");
        subMenu.add(11,12,12,"menu_11_2");
        subMenu.add(11,13,13,"menu_11_3");


        //navigationView.getMenu().add(2, 2, 2, "menu_2");

        subMenu = navigationView.getMenu().addSubMenu(1,12,12,"menu_12");

        subMenu.add(12,21,21,"menu_12_1");
        subMenu.add(12,22,22,"menu_12_2");
        subMenu.add(12,23,23,"menu_12_3");

        //navigationView.getMenu().add(3, 3, 3, "menu_3");

        subMenu = navigationView.getMenu().addSubMenu(1,13,13,"menu_13");

        subMenu.add(13,31,31,"menu_13_1");
        subMenu.add(13,32,32,"menu_13_2");


        subMenu = navigationView.getMenu().addSubMenu(1,14,14,"menu_14");

        subMenu.add(14,41,41,"menu_14_1");
        subMenu.add(14,42,42,"menu_14_2");
        subMenu.add(14,43,43,"menu_14_3");
        subMenu.add(14,44,44,"menu_14_4");
        subMenu.add(14,45,45,"menu_14_5");

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.d(TAG, "onCreateOptionsMenu");
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.company_drawer, menu);

//        menu.add(1, 1, 0, "法雨");
//        menu.add(1, 2, 1, "钓鱼郎");

        Log.d(TAG, "onCreateOptionsMenu isInitComplete:" + isInitComplete);

        for (int i = 0; i < companyList.size(); i++) {
            menu.add(1, i, i, companyList.get(i).getName());
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        int order = item.getOrder();

        Log.i(TAG, "onOptionsItemSelected id:" + id + " order:" + order);

        if (order < companyList.size()) {
            setCompany(companyList.get(order));
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        int order = item.getOrder();

        Log.i(TAG, "onNavigationItemSelected id:" + id + " order:" + order);

//        if (id == R.id.nav_camera) {
//            // Handle the camera action
//        } else if (id == R.id.nav_gallery) {
//
//        } else if (id == R.id.nav_slideshow) {
//
//        } else if (id == R.id.nav_manage) {
//
//        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
